package org.osprey.apidoc;

import io.vertx.core.*;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import org.osprey.apidoc.common.RouterVerticle;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName StartVerticle
 * @Description: 启动类Verticle
 * @Author Osprey
 * @Date 2019/10/16
 * @Version V2.0
 **/
public class StartVerticle extends AbstractVerticle implements RouterVerticle {
    public static void main(String[] args) throws IOException {
        Vertx.vertx().deployVerticle(new StartVerticle(), new DeploymentOptions().setConfig(new JsonObject(new String(Files.readAllBytes(Paths.get("config.json"))))));
    }

    @Override
    public void start(Future<Void> startFuture) throws Exception {
        super.start();

        JsonArray verticles = config().getJsonArray("verticles");

        List<Future> futures = verticles.stream()
                .map(name -> Future.<String>future(r ->
                        vertx.deployVerticle(name.toString(), new DeploymentOptions().setConfig(config()), r))
                ).collect(Collectors.toList());

        CompositeFuture.all(futures).setHandler(res -> {
            Router router = Router.router(vertx);
            routers.forEach(r -> router.route(r.getHttpMethod(), r.getApi()).handler(r.getHandler()));
            System.out.println(routers.size());
            vertx.createHttpServer().requestHandler(router).listen(config().getInteger("port"), server -> {
                if (server.succeeded()) {
                    System.out.println("server ok");
                } else {
                    server.cause().printStackTrace();
                }
            });
        });
    }
}
